HackerRank Cutting Boards
解答
code: python
import math
import os
import random
import re
import sys
#
# Complete the 'boardCutting' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER_ARRAY cost_y
# 2. INTEGER_ARRAY cost_x
#
# 1 1 2 3 4
# 1 2 4
def boardCutting(cost_y, cost_x):
# Write your code here
h = v = 1
cost_y.sort()
cost_x.sort()
i = len(cost_y) - 1
j = len(cost_x) - 1
cost = 0
while i >= 0 and j >= 0:
cut = cost_y.pop()
cost += cut * h
v += 1
i -= 1
else:
cut = cost_x.pop()
cost += cut * v
h += 1
j -= 1
if i >= 0:
cost += sum(cost_y) * h
if j >= 0:
cost += sum(cost_x) * v
return cost % (10**9 + 7)
if __name__ == '__main__':
q = int(input().strip())
for q_itr in range(q):
first_multiple_input = input().rstrip().split()
m = int(first_multiple_input0) n = int(first_multiple_input1) cost_y = list(map(int, input().rstrip().split()))
cost_x = list(map(int, input().rstrip().split()))
result = boardCutting(cost_y, cost_x)
fptr.write(str(result) + '\n')
fptr.close()
メモ
https://www.youtube.com/watch?v=GMNkBXwbZGw
https://scrapbox.io/files/61d10e86e1a3db002152bdd9.png
提出
code: python
import math
import os
import random
import re
import sys
#
# Complete the 'boardCutting' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER_ARRAY cost_y
# 2. INTEGER_ARRAY cost_x
#
def boardCutting(cost_y, cost_x):
# Write your code here
h = 1
v = 1
cost_y.sort(reverse=True)
cost_x.sort(reverse=True)
ans = 0
while len(cost_x) > 0 or len(cost_y) > 0:
if len(cost_x) == 0:
ans += cost_y.pop(0) * v
h += 1
elif len(cost_y) == 0:
ans += cost_x.pop(0) * h
v += 1
ans += cost_y.pop(0) * v
h += 1
else:
ans += cost_x.pop(0) * h
v += 1
return ans % (10**9 + 7)
if __name__ == '__main__':
q = int(input().strip())
for q_itr in range(q):
first_multiple_input = input().rstrip().split()
m = int(first_multiple_input0) n = int(first_multiple_input1) cost_y = list(map(int, input().rstrip().split()))
cost_x = list(map(int, input().rstrip().split()))
result = boardCutting(cost_y, cost_x)
fptr.write(str(result) + '\n')
fptr.close()